<template>
  <div class="user-management-container">
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增用户
        </el-button>
        <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
        <el-upload
            class="upload-demo"
            action=""
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleImport"
            accept=".xlsx, .xls"
        >
          <el-button type="warning">
            <el-icon><Upload /></el-icon>
            导入
          </el-button>
        </el-upload>
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedUsers.length === 0">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
      </div>
      <div class="toolbar-right">
        <el-input
            v-model="searchForm.keyword"
            placeholder="请输入姓名、学号或账号"
            style="width: 200px; margin-right: 10px"
            @keyup.enter="handleSearch"
            clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select v-model="searchForm.gender" placeholder="性别" style="width: 100px; margin-right: 10px" clearable>
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
          <el-option label="保密" value="保密" />
        </el-select>
        <el-cascader
            v-model="searchForm.organization"
            :options="organizationOptions"
            placeholder="组织结构"
            clearable
            style="width: 260px; margin-right: 10px"
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 用户表格 -->
    <el-table
        :data="filteredUsers"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        border
        style="width: 100%"
        height="500"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="姓名" width="100" />
      <el-table-column prop="gender" label="性别" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.gender === '男' ? 'primary' : scope.row.gender === '女' ? 'success' : 'info'">
            {{ scope.row.gender }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="stuId" label="学号" width="120" />
      <el-table-column prop="account" label="账号" width="120" />
      <el-table-column prop="contact" label="联系方式" width="120" />
      <el-table-column prop="organizationText" label="所属组织" min-width="200" />
      <el-table-column prop="lastLogin" label="最后登录" width="160" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="info" link @click="handleView(scope.row)">查看</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 用户编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="600px"
        @close="handleDialogClose"
    >
      <el-form
          ref="userFormRef"
          :model="userForm"
          :rules="userFormRules"
          label-width="80px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="userForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="userForm.gender" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
                <el-option label="保密" value="保密" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学号" prop="stuId">
              <el-input v-model="userForm.stuId" placeholder="请输入学号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账号" prop="account">
              <el-input v-model="userForm.account" placeholder="请输入账号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="contact">
              <el-input v-model="userForm.contact" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="所属组织" prop="organization">
          <el-cascader
              v-model="userForm.organization"
              :options="organizationOptions"
              placeholder="请选择所属组织"
              style="width: 100%"
              @change="handleOrganizationChange"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 用户详情对话框 -->
    <el-dialog
        v-model="viewDialogVisible"
        title="用户详情"
        width="500px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="姓名">{{ currentUser.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">{{ currentUser.gender }}</el-descriptions-item>
        <el-descriptions-item label="学号">{{ currentUser.stuId }}</el-descriptions-item>
        <el-descriptions-item label="账号">{{ currentUser.account }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ currentUser.contact }}</el-descriptions-item>
        <el-descriptions-item label="所属组织">{{ currentUser.organizationText }}</el-descriptions-item>
        <el-descriptions-item label="最后登录" :span="2">{{ currentUser.lastLogin }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Upload, Delete, Search } from '@element-plus/icons-vue'
import { utils, writeFileXLSX } from 'xlsx'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogTitle = ref('')
const userFormRef = ref()
const selectedUsers = ref([])
const currentUser = ref({})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  gender: '',
  organization: undefined
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 用户表单
const userForm = reactive({
  id: null,
  name: '',
  gender: '',
  stuId: '',
  account: '',
  password: '',
  contact: '',
  organization: [],
  organizationText: ''
})

// 表单验证规则
const userFormRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  stuId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  organization: [{ required: true, message: '请选择所属组织', trigger: 'change' }]
}

// 组织架构选项 - 河南工业和信息化职业学院四级结构
const organizationOptions = [
  {
    value: '河南工业和信息化职业学院',
    label: '河南工业和信息化职业学院',
    children: [
      {
        value: '计算机应用技术',
        label: '计算机应用技术',
        children: [
          {
            value: '2025级',
            label: '2025级',
            children: [
              { value: '1班', label: '1班' },
              { value: '2班', label: '2班' },
              { value: '3班', label: '3班' }
            ]
          },
          {
            value: '2024级',
            label: '2024级',
            children: [
              { value: '1班', label: '1班' },
              { value: '2班', label: '2班' },
              { value: '3班', label: '3班' }
            ]
          },
          {
            value: '2023级',
            label: '2023级',
            children: [
              { value: '1班', label: '1班' },
              { value: '2班', label: '2班' },
              { value: '3班', label: '3班' }
            ]
          },
          {
            value: '2022级',
            label: '2022级',
            children: [
              { value: '1班', label: '1班' },
              { value: '2班', label: '2班' },
              { value: '3班', label: '3班' }
            ]
          }
        ]
      }
    ]
  }
]

// 用户数据 - 关联河南工业和信息化职业学院四级结构
const users = ref([
    {
    id: 1,
    name: '李明',
    gender: '男',
    stuId: '20222154521',
    account: 'LM20250902',
    password: '123456',
    contact: '-',
    organization: ['河南工业和信息化职业学院', '计算机应用技术', '2025级', '1班'],
    organizationText: '河南工业和信息化职业学院,计算机应用技术,2025级,1班',
    lastLogin: '2023-03-02 22:33'
  },
  {
    id: 2,
    name: '李四',
    gender: '男',
    stuId: '20252154522',
    account: 'lisi002',
    password: '123456',
    contact: '-',
    organization: ['河南工业和信息化职业学院', '计算机应用技术', '2025级', '2班'],
    organizationText: '河南工业和信息化职业学院,计算机应用技术,2025级,2班',
    lastLogin: '2023-03-02 22:33'
  },
  {
    id: 3,
    name: '王五',
    gender: '男',
    stuId: '20252154523',
    account: 'wangwu003',
    password: '123456',
    contact: '-',
    organization: ['河南工业和信息化职业学院', '计算机应用技术', '2025级', '3班'],
    organizationText: '河南工业和信息化职业学院,计算机应用技术,2025级,3班',
    lastLogin: '2023-02-27 11:01'
  },
  {
    id: 4,
    name: '赵六',
    gender: '女',
    stuId: '20242154524',
    account: 'zhaoliu004',
    password: '123456',
    contact: '13110196219',
    organization: ['河南工业和信息化职业学院', '计算机应用技术', '2024级', '1班'],
    organizationText: '河南工业和信息化职业学院,计算机应用技术,2024级,1班',
    lastLogin: '2023-01-04 11:30'
  },
  {
    id: 5,
    name: '孙七',
    gender: '女',
    stuId: '20242154525',
    account: 'sunqi005',
    password: '123456',
    contact: '13900000001',
    organization: ['河南工业和信息化职业学院', '计算机应用技术', '2024级', '2班'],
    organizationText: '河南工业和信息化职业学院,计算机应用技术,2024级,2班',
    lastLogin: '2023-03-05 09:10'
  },
  {
    id: 6,
    name: '周八',
    gender: '男',
    stuId: '20242154526',
    account: 'zhouba006',
    password: '123456',
    contact: '13800000002',
    organization: ['河南工业和信息化职业学院', '计算机应用技术', '2024级', '3班'],
    organizationText: '河南工业和信息化职业学院,计算机应用技术,2024级,3班',
    lastLogin: '2023-02-14 15:35'
  },
  {
    id: 7,
    name: '吴九',
    gender: '男',
    stuId: '20232154527',
    account: 'wujiu007',
    password: '123456',
    contact: '-',
    organization: ['河南工业和信息化职业学院', '计算机应用技术', '2023级', '1班'],
    organizationText: '河南工业和信息化职业学院,计算机应用技术,2023级,1班',
    lastLogin: '2023-03-06 19:24'
  },
  { id: 8,
    name: '郑十',
    gender: '女',
    stuId: '20232154528',
    account: 'zhengshi008',
    password: '123456',
    contact: '13700000003',
    organization: ['河南工业和信息化职业学院', '计算机应用技术', '2023级', '2班'],
    organizationText: '河南工业和信息化职业学院,计算机应用技术,2023级,2班',
    lastLogin: '2022-04-24 14:18'
  },
  { id: 9,
    name: '钱一',
    gender: '男',
    stuId: '20232154529',
    account: 'qianyi009',
    password: '123456',
    contact: '13600000004',
    organization: ['河南工业和信息化职业学院', '计算机应用技术', '2023级', '3班'],
    organizationText: '河南工业和信息化职业学院,计算机应用技术,2023级,3班',
    lastLogin: '2023-03-08 08:20'
  },
  { id: 10,
    name: '孙二',
    gender: '女',
    stuId: '20222154530',
    account: 'suner010',
    password: '123456',
    contact: '13500000005',
    organization: ['河南工业和信息化职业学院', '计算机应用技术', '2022级', '1班'],
    organizationText: '河南工业和信息化职业学院,计算机应用技术,2022级,1班',
    lastLogin: '2023-01-12 10:00'
  }
])

// 显示的用户数据（经过搜索筛选后的数据）
const filteredUsers = ref([])

// 搜索状态
const isSearching = ref(false)

// 方法
const handleAdd = () => {
  dialogTitle.value = '新增用户'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  // 复制用户数据到表单，包括organization数组
  userForm.id = row.id
  userForm.name = row.name
  userForm.gender = row.gender
  userForm.stuId = row.stuId
  userForm.account = row.account
  userForm.password = row.password
  userForm.contact = row.contact
  userForm.organization = [...row.organization] // 复制数组
  userForm.organizationText = row.organizationText
  dialogVisible.value = true
}

const handleView = (row) => {
  currentUser.value = { ...row }
  viewDialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除用户 "${row.name}" 吗？`, '提示', { type: 'warning' })
      .then(() => {
        const index = users.value.findIndex(user => user.id === row.id)
        if (index > -1) {
          users.value.splice(index, 1)
          ElMessage.success('删除成功')
        }
      })
      .catch(() => {})
}

const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定删除选中的 ${selectedUsers.value.length} 个用户吗？`, '提示', { type: 'warning' })
      .then(() => {
        selectedUsers.value.forEach(selectedUser => {
          const index = users.value.findIndex(user => user.id === selectedUser.id)
          if (index > -1) {
            users.value.splice(index, 1)
          }
        })
        selectedUsers.value = []
        ElMessage.success('批量删除成功')
      })
      .catch(() => {})
}

const handleSelectionChange = (selection) => {
  selectedUsers.value = selection
}

const handleSearch = () => {
  isSearching.value = true
  pagination.currentPage = 1

  // 执行搜索筛选
  let result = [...users.value]

  // 关键词搜索
  if (searchForm.keyword) {
    result = result.filter(user =>
        user.name.includes(searchForm.keyword) ||
        user.stuId.includes(searchForm.keyword) ||
        user.account.includes(searchForm.keyword)
    )
  }

  // 性别筛选
  if (searchForm.gender) {
    result = result.filter(user => user.gender === searchForm.gender)
  }

  // 组织结构筛选
  if (searchForm.organization && searchForm.organization.length) {
    // 将选择的组织结构数组转换为字符串，用于比较
    const selectedOrg = Array.isArray(searchForm.organization) ? searchForm.organization.join(',') : String(searchForm.organization)
    // 确保用户的组织结构包含选择的所有层级（前缀匹配）
    result = result.filter(u => {
      // 检查用户的组织结构文本是否以选择的组织结构开头
      return u.organizationText.startsWith(selectedOrg) || 
             // 或者用户的组织结构数组完全包含选择的组织结构数组
             (Array.isArray(searchForm.organization) && 
              searchForm.organization.every((level, index) => u.organization[index] === level))
    })
  }

  // 更新显示数据
  filteredUsers.value = result
  pagination.total = result.length

  // 更新分页显示
  updateDisplayData()

  ElMessage.success(`搜索完成，找到 ${result.length} 条记录`)
}

const handleReset = () => {
  searchForm.keyword = ''
  searchForm.gender = ''
  searchForm.organization = undefined
  pagination.currentPage = 1
  isSearching.value = false
  pagination.total = users.value.length
  updateDisplayData()
  ElMessage.success('已重置搜索条件')
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  updateDisplayData()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  updateDisplayData()
}

// 更新显示数据（分页）
const updateDisplayData = () => {
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  const dataSource = isSearching.value ? filteredUsers.value : users.value
  const paginatedData = dataSource.slice(start, end)
  filteredUsers.value = paginatedData
}

const handleSubmit = () => {
  userFormRef.value.validate((valid) => {
    if (valid) {
      if (userForm.id) {
        // 编辑 - 确保organizationText与organization数组同步
        const index = users.value.findIndex(user => user.id === userForm.id)
        if (index > -1) {
          // 更新organizationText以匹配organization数组
          const orgText = Array.isArray(userForm.organization) ? userForm.organization.join(',') : userForm.organizationText

          // 更新用户数据
          users.value[index] = {
            ...userForm,
            organizationText: orgText
          }

          // 重新更新显示数据以确保表格刷新
          updateDisplayData()
          ElMessage.success('编辑成功')
        }
      } else {
        // 新增
        userForm.id = Date.now()
        const orgText = Array.isArray(userForm.organization) ? userForm.organization.join(',') : userForm.organizationText
        users.value.unshift({
          ...userForm,
          organizationText: orgText,
          lastLogin: new Date().toLocaleString()
        })
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
    }
  })
}

const handleDialogClose = () => {
  resetForm()
  userFormRef.value?.resetFields()
}

const resetForm = () => {
  Object.assign(userForm, {
    id: null,
    name: '',
    gender: '',
    stuId: '',
    account: '',
    password: '',
    contact: '',
    organization: [],
    organizationText: ''
  })
}

const handleOrganizationChange = (value) => {
  userForm.organizationText = value.join(',')
}

const handleImport = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const data = new Uint8Array(e.target.result)
      const workbook = utils.read(data, { type: 'array' })
      const worksheet = workbook.Sheets[workbook.SheetNames[0]]
      const jsonData = utils.sheet_to_json(worksheet)

      // 处理导入的数据
      const importedUsers = jsonData.map((item, index) => ({
        id: Date.now() + index,
        name: item['姓名'] || '',
        gender: item['性别'] || '保密',
        stuId: item['学号'] || '',
        account: item['账号'] || '',
        password: item['密码'] || '123456',
        contact: item['联系方式'] || '-',
        organization: item['所属组织'] ? item['所属组织'].split(',') : [],
        organizationText: item['所属组织'] || '',
        lastLogin: item['最后登录'] || new Date().toLocaleString()
      }))

      users.value = [...importedUsers, ...users.value]
      ElMessage.success(`成功导入 ${importedUsers.length} 条用户数据`)
    } catch (error) {
      ElMessage.error('导入失败，请检查文件格式')
    }
  }
  reader.readAsArrayBuffer(file.raw)
}

const handleExport = () => {
  const exportData = users.value.map(user => ({
    '姓名': user.name,
    '性别': user.gender,
    '学号': user.stuId,
    '账号': user.account,
    '密码': user.password,
    '联系方式': user.contact,
    '所属组织': user.organizationText,
    '最后登录': user.lastLogin
  }))

  const ws = utils.json_to_sheet(exportData)
  const wb = utils.book_new()
  utils.book_append_sheet(wb, ws, '用户数据')
  writeFileXLSX(wb, '用户数据.xlsx')
  ElMessage.success('导出成功')
}

// 初始化
onMounted(() => {
  pagination.total = users.value.length
  updateDisplayData()
})
</script>

<style lang="scss" scoped>
.user-management-container {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.06);
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;

  .toolbar-left {
    display: flex;
    gap: 8px;
  }

  .toolbar-right {
    display: flex;
    align-items: center;
  }
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 16px 0;
}

.upload-demo {
  display: inline-block;
}
</style>
